package utils;

import android.content.Context;
import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zhenglikun on 2017/3/3.
 */

public class RetrofitWrapper {
    private static RetrofitWrapper instance;
    private Retrofit mRetrofit;
    private Context mContext;
    private OkHttpClient client;

    public RetrofitWrapper(Context context, String url) {

        mContext = context;

        createClient();
        mRetrofit = new Retrofit.Builder().baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }

    private void createClient() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // Log
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Log.w("RetrofitWrapper", message));
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = builder
                .addInterceptor(logging)
                .connectTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .build();
    }

    public static RetrofitWrapper getInstance(Context context, String url) {

        if (null == instance) {
            synchronized (RetrofitWrapper.class) {
                if (instance == null) {
                    instance = new RetrofitWrapper(context.getApplicationContext(), url);
                }
            }
        }
        return instance;
    }

    public static RetrofitWrapper getInstance(Context context, boolean changeUrl, String url) {
        if (null == instance) {
            synchronized (RetrofitWrapper.class) {
                if (instance == null) {
                    instance = new RetrofitWrapper(context.getApplicationContext(), url);
                }
            }
        }
        if (changeUrl) {
            instance.mRetrofit = new Retrofit.Builder().baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(instance.client)
                    .build();
        }
        return instance;
    }

    public <T> T create(final Class<T> service) {
        return mRetrofit.create(service);
    }

    public <T> T createByURL(final Class<T> service, String url) {
        return new Retrofit.Builder().baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build().create(service);
    }

}
